// Require objects.
var aws = require("aws-sdk");
const Sequelize = require("sequelize");
var queueUrl =
  "https://sqs.cn-northwest-1.amazonaws.com.cn/535137518543/aitask";
var receipt = "";

var awsSentMessage = function(sqs, params) {
  return new Promise(function(resolve, reject) {
    sqs.sendMessage(params, function(err, data) {
      if (err) {
        console.log("aws send message error: ", err);
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

// Load your AWS credentials and try to instantiate the object.
aws.config.loadFromPath(__dirname + "/config.json");

// Instantiate SQS.
var sqs = new aws.SQS();

/* // Creating a queue.
app.get('/create', function (req, res) {
    var params = {
        QueueName: "MyFirstQueue"
    };
    
    sqs.createQueue(params, function(err, data) {
        if(err) {
            res.send(err);
        } 
        else {
            res.send(data);
        } 
    });
});

// Listing our queues.
app.get('/list', function (req, res) {
    sqs.listQueues(function(err, data) {
        if(err) {
            res.send(err);
        } 
        else {
            res.send(data);
        } 
    });
}); */

// Sending a message.
// NOTE: Here we need to populate the queue url you want to send to.
// That variable is indicated at the top of app.js

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  "postgres://postgres:password@localhost:6432/postgres";

async function sentAiTaskMessage(newAiTaskReq) {
  const messageBody = {
    id: newAiTaskReq.id
  };
  try {
    var params = {
      MessageBody: JSON.stringify(messageBody),
      QueueUrl: queueUrl,
      DelaySeconds: 0
    };
    var res = await awsSentMessage(sqs, params);
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
    var res = await sequelize.query(
      "UPDATE ai_lab_task SET state= :status WHERE id = :id",
      {
        replacements: {
          id: newAiTaskReq.id,
          status: "queued"
        }
      }
    );
    return res;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.sentAiTaskMessage = sentAiTaskMessage;

/* // Receive a message.
// NOTE: This is a great long polling example. You would want to perform
// this action on some sort of job server so that you can process these
// records. In this example I'm just showing you how to make the call.
// It will then put the message "in flight" and I won't be able to 
// reach that message again until that visibility timeout is done.
app.get('/receive', function (req, res) {
    var params = {
        QueueUrl: queueUrl,
        VisibilityTimeout: 600 // 10 min wait time for anyone else to process.
    };
    
    sqs.receiveMessage(params, function(err, data) {
        if(err) {
            res.send(err);
        } 
        else {
            res.send(data);
        } 
    });
});

// Deleting a message.
app.get('/delete', function (req, res) {
    var params = {
        QueueUrl: queueUrl,
        ReceiptHandle: receipt
    };
    
    sqs.deleteMessage(params, function(err, data) {
        if(err) {
            res.send(err);
        } 
        else {
            res.send(data);
        } 
    });
});

// Purging the entire queue.
app.get('/purge', function (req, res) {
    var params = {
        QueueUrl: queueUrl
    };
    
    sqs.purgeQueue(params, function(err, data) {
        if(err) {
            res.send(err);
        } 
        else {
            res.send(data);
        } 
    });
}); */
